package com.spc.car.data.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spc.car.common.exception.CustomException;
import com.spc.car.data.domain.project.dto.BiddingBondListDTO;
import com.spc.car.data.domain.project.vo.ProjectBiddingEnteredVO;
import com.spc.car.data.entity.project.ProjectBiddingEntered;
import com.spc.car.data.mapper.project.ProjectBiddingEnteredMapper;
import com.spc.car.data.service.project.ProjectBiddingEnteredService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 投标人报名表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-04-02
 */
@Service
public class ProjectBiddingEnteredServiceImpl extends ServiceImpl<ProjectBiddingEnteredMapper, ProjectBiddingEntered> implements ProjectBiddingEnteredService {

    @Override
    public void addBiddingEntered(ProjectBiddingEnteredVO enteredVO) {

        boolean result = toCheck(enteredVO);
        if (result) {
            ProjectBiddingEntered projectBiddingEntered = new ProjectBiddingEntered();
            BeanUtils.copyProperties(enteredVO, projectBiddingEntered);
            if (!ObjectUtils.isNotEmpty(enteredVO.getId())) {
                projectBiddingEntered.setModifyTime(new Date());
                updateById(projectBiddingEntered);
            }
            projectBiddingEntered.setCreateTime(new Date());
            saveOrUpdate(projectBiddingEntered);
        }
    }

    @Override
    public List<BiddingBondListDTO> listProjectBiddingBond(@NotBlank String projectCode,
                                                           @NotBlank String sectionCode) {
        return baseMapper.listProjectBiddingBond(projectCode, sectionCode);
    }


    /**
     * 检测是否存在相同的投标信息
     * @return
     */
    private boolean toCheck(ProjectBiddingEnteredVO enteredVO) {

        List<ProjectBiddingEntered> biddingEntereds =
                list(new LambdaQueryWrapper<ProjectBiddingEntered>()
                        .eq(ProjectBiddingEntered::getProjectCode, enteredVO.getProjectCode()));

        biddingEntereds.stream().forEach(biddingEntered-> {
            if (biddingEntered.getEnteredOrgCode().equals(enteredVO.getEnteredOrgCode())) {
                throw new CustomException("同一项目下不能有相同的机构信息！");
            }

            if (biddingEntered.getMobile().equals(enteredVO.getMobile())) {
                throw new CustomException("此号码已在该项目下使用！");
            }
        });
        return true;
    }

}
